package demo2;
import java.util.*;
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-07-05
 * Time: 16:41
 */
class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> cnt = new HashMap<String, Integer>();
        for (String word : words) {
            cnt.put(word, cnt.getOrDefault(word, 0) + 1);
        }
        PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<Map.Entry<String, Integer>>
                (new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) {
                return entry1.getValue() == entry2.getValue() ?
                        entry2.getKey().compareTo(entry1.getKey()) :
                        entry1.getValue() - entry2.getValue();
            }
        });
        for (Map.Entry<String, Integer> entry : cnt.entrySet()) {
            pq.offer(entry);
            if (pq.size() > k) {
                pq.poll();
            }
        }
        List<String> ret = new ArrayList<String>();
        while (!pq.isEmpty()) {
            ret.add(pq.poll().getKey());
        }
        Collections.reverse(ret);
        return ret;
    }
}
public class MapTest {

    public static void main(String[] args) {
        Solution solution = new Solution();
        String[] words = {"i", "love", "leetcode", "i", "love", "coding"};
        solution.topKFrequent(words,2);
    }

    public static void main3(String[] args) {

        Map<String,Integer> map = new HashMap<>();
        //key不可以重复，value可以一样
        map.put("A",2);
        map.put("B",5);
        map.put("C",6);
        map.put("D",9);
        map.put("E",1);
        map.put("A",9);
        System.out.println("===========");
        System.out.println(map);
        System.out.println(map.size());
        System.out.println(map);
        //get方法返回key对应的value值，如果没有key存在就会返回null
        System.out.println(map.get("A"));
        System.out.println(map.get("P"));
        System.out.println("===========");
        //contains方法查找是否存在key     O(logN)
        System.out.println(map.containsKey("T"));
        System.out.println(map.containsKey("A"));
        //contains方法查找是否存在value   O(N)
        System.out.println(map.containsValue(8));
        System.out.println(map.containsValue(6));
        System.out.println("===================");
        //map.keySet方法存储所有的key值
        for (String s:map.keySet()) {
            System.out.print(s);
        }
        System.out.println("==============");
        for (Integer e:map.values()) {
            System.out.print(e+" ");
        }
        System.out.println("==============");
        for (Map.Entry<String,Integer> entry:map.entrySet()) {
            System.out.println(entry.getKey()+"---->"+entry.getValue());
        }



    }

}
